package org.go.smart;

import java.text.DecimalFormat;

import org.go.smart.log.GSLogger;
import org.go.smart.settings.SettingsBean;
import org.go.smart.temperature.StubTemperatureController;
import org.go.smart.temperature.TemperatureControllerApi;

public class RoomController {
	
	private final String name;
	
	private DecimalFormat decimalFormat = new DecimalFormat("#.#");
	private TemperatureControllerApi temperatureController;
	
	public RoomController(final String name) {
		this.name = name;
		this.temperatureController = new StubTemperatureController();
		((StubTemperatureController)temperatureController).start();
	}

	public String getName() {
		return name;
	}
	
	public String getReadTemperature() {
		if (temperatureController.getReadTemperature() == HouseController.NOT_INITIALISED_VALUE) {
			return "n/a";
		}
		return decimalFormat.format(temperatureController.getReadTemperature());
	}
	
	public String getWantedTemperature() {
		if (temperatureController.getWantedTemperature() == HouseController.NOT_INITIALISED_VALUE) {
			return "n/a";
		}
		return decimalFormat.format(temperatureController.getWantedTemperature());
	}
	
	public void setWantedTemperature(final String wantedTemperature) {
		String oldTemp = this.temperatureController.getWantedTemperature() == HouseController.NOT_INITIALISED_VALUE ? "N/A" : ("" + this.temperatureController.getWantedTemperature());
		this.temperatureController.setWantedTemperature(Double.parseDouble(wantedTemperature));
		GSLogger.getInstance().info("Wanted temperature changed from " + oldTemp + " to " + wantedTemperature);
	}
	
	public boolean shouldStartHeater() {
		if (temperatureController.getWantedTemperature() != HouseController.NOT_INITIALISED_VALUE) {
			return temperatureController.getReadTemperature() < (temperatureController.getWantedTemperature() - SettingsBean.getInstance().getTemperatureThreshold());
		}
		return false;
	}
	
	public boolean shouldStartAC() {
		if (temperatureController.getWantedTemperature() != HouseController.NOT_INITIALISED_VALUE) {
			return temperatureController.getReadTemperature() > (temperatureController.getWantedTemperature() + SettingsBean.getInstance().getTemperatureThreshold());
		}
		return false;
	}
	
	public boolean shouldStopHeater() {
		if (temperatureController.getWantedTemperature() != HouseController.NOT_INITIALISED_VALUE) {
			return temperatureController.getReadTemperature() >= (temperatureController.getWantedTemperature());
		}
		return false;
	}
	
	public boolean shouldStopAC() {
		if (temperatureController.getWantedTemperature() != HouseController.NOT_INITIALISED_VALUE) {
			return temperatureController.getReadTemperature() <= (temperatureController.getWantedTemperature());
		}
		return false;
	}
}
